package cn.cheniy.swiftmark.search.canal;

import cn.throwx.canal.gule.model.ModelTable;
import cn.throwx.canal.gule.support.processor.BaseCanalBinlogEventProcessor;
import cn.throwx.canal.gule.support.processor.CanalBinlogEventProcessorFactory;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author cheniy
 * @description
 *
 */
public class SwiftMarkCanalBinlogEventProcessorFactory implements CanalBinlogEventProcessorFactory {

    // 将实例化的Canal处理器收集为List
    private final ConcurrentMap<ModelTable, List<BaseCanalBinlogEventProcessor<?>>> cache = new ConcurrentHashMap<>(16);

    /**
     * 将ModelTable和canal处理器一一对应
     *
     * @param modelTable 含义数据库和表的实体
     * @param processor
     */
    @Override
    public void register(ModelTable modelTable, BaseCanalBinlogEventProcessor<?> processor) {
        synchronized(this.cache) {
            this.cache.putIfAbsent(modelTable, new LinkedList<>());
            this.cache.get(modelTable).add(processor);
        }
    }

    /**
     * 根据ModelTable获取到对应的处理
     * @param modelTable 含义数据库和表的实体
     * @return
     */
    @Override
    public List<BaseCanalBinlogEventProcessor<?>> get(ModelTable modelTable) {
        return this.cache.get(modelTable);
    }

    private SwiftMarkCanalBinlogEventProcessorFactory() {
    }

    public static SwiftMarkCanalBinlogEventProcessorFactory of() {
        return new SwiftMarkCanalBinlogEventProcessorFactory();
    }
}
